<template>
  <div>
    <el-table border stripe :data="fileData">
      <el-table-column
        v-for="(column,index) in fileColumn"
        :key="index"
        :label="column.label"
        :width="column.width"
        :align="column.align"
      >
        <template slot-scope="scope">
          <div v-if="column.prop==='name'">
            <span v-for="(file, fileIndex) in scope.row.fileList" :key="file.name || file.oldFileName" class="file-item">
              <a v-if="file.oldFileName" class="download-link" @click="dowuloadP(file)">
                <span>{{ `${file.oldFileName}` }}</span>
              </a>
              <span v-else>
                <span>{{ `${file.name}` }}</span>
              </span>
              <i v-if="!checkFlag" :class="isMouse?'el-icon-circle-check':'el-icon-close'" @mouseover="isMouse=false" @mouseleave="isMouse=true" @click="fakeDeleteFile(scope.row, file, fileIndex)" />
              <span>{{ `${fileIndex === scope.row.fileList.length - 1? '': '；'}` }}</span>
            </span>
          </div>
          <div v-else>
            <span>{{ scope.row[column.prop] }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        v-if="!checkFlag"
        label="操作"
        width="80"
        align="center"
      >
        <template slot-scope="scope">
          <el-upload
            :ref="`commonUpload${scope.row.refStr}`"
            :action="`?businessId=${scope.row.businessId}&sysCode=personManage&businessNode=${scope.row.businessNode}`"
            :auto-upload="false"
            multiple
            :on-change="fileChange(scope.row, scope.$index)"
            :show-file-list="false"
            :with-credentials="true"
            :http-request="upload"
            :accept="getAcceptType()"
            :limit="scope.row.limit || 10"
            :on-exceed="(files, fileList)=>handleExceed(files, fileList,scope.row.limit)"
            :file-list="scope.row.fileList"
          >
            <el-button size="mini-1" type="text">上传</el-button>
          </el-upload>
        </template>
      </el-table-column>
    </el-table>
    <cus-image
      style="width: 0;"
      :src="url"
      :preview-src-list="srcList"
      ref="previewImg"
      @onload="onload">
    </cus-image>
    <!-- <el-dialog title="预览" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
      <span slot="footer" class="dialog-footer">
        <el-button @click="onload">下载</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>

<script>
import { fileColumn } from './data'
import { handleChange2 } from '@/utils'
import { upload, deleteFile } from '@/api/app'
import cusImage from "../CusImage/cusImage.vue";
export default {
  props: {
    fileData: {
      type: Array,
      default: () => {
        return []
      }
    },
    checkFlag: {
      type: Boolean,
      default: false
    }
  },
  components:{
    cusImage
  },
  data() {
    return {
      url: '',
      srcList: [],
      isMouse: true,
      fileColumn,
      dialogVisible: false,
      dialogImageUrl: '',
      onloadId: '',
      allUploadInfo: [],
      allDeleteInfo: []
    }
  },
  methods: {
    onload() {
      this.dialogVisible = false
      location.href = `/comm-file-server/file/download?fileId=${this.onloadId}`
    },
    isAssetTypeAnImage(ext) {
      return [
        'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff']
        .indexOf(ext.toLowerCase()) !== -1
    },
    dowuloadP(file) {
      var indexLeng = file.oldFileName.indexOf('.') + 1
      var indexName = file.oldFileName.substring(indexLeng)
      if (this.isAssetTypeAnImage(indexName)) {
        // this.dialogVisible = true
        this.onloadId = file.id
        this.dialogImageUrl = `/comm-file-server/file/download?fileId=${file.id}`
        //图片预览
        this.url = `/comm-file-server/file/download?fileId=${file.id}`
        this.srcList = [`/comm-file-server/file/download?fileId=${file.id}`]
        this.$refs.previewImg.cusPreviewImage()
      } else {
        location.href = `/comm-file-server/file/download?fileId=${file.id}`
      }
    },
    handleExceed(files, fileList, limit) {
      if (!limit) {
        limit = 10
      }
      this.$my_message.warning(`文件数量不能超过${limit}个`)
    },
    fileChange(row, index) {
      return (file, fileList) => {
        this.fileData[index].currentFileList = fileList
        if (file.status === 'ready') {
          // 校验文件大小
          if (!(file.size / 1024 / 1024 < 5)) {
            this.$my_message.warning('上传材料大小不能超过5MB!')
            return fileList.pop()
          }
          // 校验文件大小
          if (file.size === 0) {
            this.$my_message.warning('上传文件不能为空')
            return fileList.pop()
          }
          this.fileData[index].fileList.push(file)
          handleChange2(file, this.fileData[index].fileList)
        }
        if (file.status === 'fail') {
          // 如果文件上传失败，将文件从展示的文件列表中删除
          const fileIndex = this.fileData[index].fileList.findIndex(f => f.name === file.name)
          this.fileData[index].fileList.splice(fileIndex, 1)
        }
      }
    },
    upload(params) {
    },
    // 页面删除
    fakeDeleteFile(row, file, index) {
      if (file.id || file.uploadedFileId) {
        this.allDeleteInfo.push(file.id || file.uploadedFileId)
      } else {
        // 如果是待上传的文件，需要在上传文件的组件中将该文件删除
        const fileInx = row.currentFileList.findIndex(item => item.name === file.name)
        row.currentFileList.splice(fileInx, 1)
      }
      // 页面中删除
      row.fileList.splice(index, 1)
    },
    async submit(draft) {
      if (draft) {
        // 如果是草稿箱删除，真正去删除文件否则不删除
        while (this.allDeleteInfo.length > 0) {
          await deleteFile({
            fileId: this.allDeleteInfo[0]
          })
          this.allDeleteInfo.splice(0, 1)
        }
      }
      for (let i = 0; this.fileData.length > i; i++) {
        for (let j = 0; this.fileData[i].fileList.length > j; j++) {
          if (!this.fileData[i].fileList[j].isUploaded && !this.fileData[i].fileList[j].id) {
            try {
              const formData = new FormData()
              formData.append('file', this.fileData[i].fileList[j].raw)
              const { data } = await upload(`?businessId=${this.fileData[i].businessId}&sysCode=personManage&businessNode=${this.fileData[i].businessNode}`,
                formData)
                this.fileData[i].fileList[j] = {...data}
              this.fileData[i].fileList[j].isUploaded = true
              this.fileData[i].fileList[j].uploadedFileId = data.id
            } catch (err) {
              console.error(err)
              return Promise.reject('上传出错')
            }
          }
        }
      }
      return Promise.resolve([])
    },
    getAcceptType() {
      return this.$route.query.type === 'basicPage' ? 'image/*' : ''
    },
    isUploaded(params) {
      return !!this.allUploadInfo.find(item => item.file.uid === params.file.uid)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-icon-circle-check:before{
  color:rgb(117, 195, 94)
}
/deep/ .el-dialog__body {
  padding: 10px 20px;
  img{
    max-width: 500px;
    max-height: 500px;
  }
}
/deep/ .el-dialog__footer{
  padding-top: 0;
  padding-bottom: 10px;
}
</style>
